﻿Imports System.Web
Imports System.Web.Services
Imports System.Text

Namespace DotNetNuke.Modules.ActiveForums.Handlers
    Public Class adminhelper
        Inherits HandlerBase
        Public Enum Actions
            None
            PropertySave = 2
            PropertyDelete = 3
            PropertyList = 4
            PropertySortSwitch = 5
            ListOfLists = 6
            LoadView = 7
            RankGet = 8
            RankSave = 9
            RankDelete = 10
            FilterGet = 11
            FilterSave = 12
            FilterDelete = 13


            
        End Enum
        Overrides Sub ProcessRequest(ByVal context As HttpContext)
            AdminRequired = True
            MyBase.AdminRequired = True
            MyBase.ProcessRequest(context)
            Dim sOut As String = String.Empty
            Dim action As Actions = Actions.None
            If IsValid Then
                If Not Params Is Nothing Then
                    If Not Params("action") Is Nothing AndAlso IsNumeric(Params("action")) Then
                        action = CType(CInt(Params("action").ToString), Actions)
                    End If
                End If
                Try
                    sOut = "{""result"":""success""}"
                    Select Case action
                        Case Actions.PropertySave
                            PropertySave()
                        Case Actions.PropertyDelete
                            PropertyDelete()
                        Case Actions.PropertyList
                            sOut = "[" & Utilities.LocalizeControl(PropertyList()) & "]"
                        Case Actions.PropertySortSwitch
                            UpdateSort()
                        Case Actions.ListOfLists
                            sOut = GetLists()
                        Case Actions.LoadView
                            sOut = LoadView()
                        Case Actions.RankGet
                            sOut = GetRank()
                        Case Actions.RankSave
                            RankSave()
                        Case Actions.RankDelete
                            RankDelete()
                        Case Actions.FilterGet
                            sOut = FilterGet()
                        Case Actions.FilterSave
                            FilterSave()
                        Case Actions.FilterDelete
                            FilterDelete()




                    End Select
                Catch ex As Exception
                    Exceptions.LogException(ex)
                    sOut = "{"
                    sOut &= Utilities.JSON.Pair("result", "failed")
                    sOut &= ","
                    sOut &= Utilities.JSON.Pair("message", ex.Message)
                    sOut &= "}"
                End Try

            Else
                sOut = "{"
                sOut &= Utilities.JSON.Pair("result", "failed")
                sOut &= ","
                sOut &= Utilities.JSON.Pair("message", "Invalid Request")
                sOut &= "}"
            End If
            context.Response.ContentType = "text/plain"
            context.Response.Write(sOut)
        End Sub
        Private Function FilterGet() As String
            Dim FilterId As Integer = -1
            If Params.ContainsKey("FilterId") Then
                FilterId = Convert.ToInt32(Params("FilterId"))
            End If
            Dim fc As New FilterController
            Dim filter As FilterInfo = fc.Filter_Get(PortalId, ModuleId, FilterId)
            Dim sOut As String = "{"
            sOut &= Utilities.JSON.Pair("FilterId", filter.FilterId.ToString())
            sOut &= ","
            sOut &= Utilities.JSON.Pair("FilterType", filter.FilterType.ToString())
            sOut &= ","
            sOut &= Utilities.JSON.Pair("Find", HttpUtility.UrlEncode(filter.Find.Replace(" ", "-|-")))
            sOut &= ","
            sOut &= Utilities.JSON.Pair("Replacement", HttpUtility.UrlEncode(filter.Replace.Replace(" ", "-|-")))
            sOut &= "}"
            Return sOut
        End Function
        Private Sub FilterSave()
            Dim filter As New FilterInfo()
            filter.FilterId = -1
            filter.ModuleId = ModuleId
            filter.PortalId = PortalId
            If Params.ContainsKey("FilterId") Then
                filter.FilterId = Convert.ToInt32(Params("FilterId"))
            End If
            If Params.ContainsKey("Find") Then
                filter.Find = Params("Find").ToString()
            End If
            If Params.ContainsKey("Replacement") Then
                filter.Replace = Params("Replacement").ToString()
            End If
            If Params.ContainsKey("FilterType") Then
                filter.FilterType = Params("FilterType").ToString()
            End If
  
            Dim fc As New FilterController
            filter = fc.Filter_Save(filter)
        End Sub
        Private Sub FilterDelete()
            Dim FilterId As Integer = -1
            If Params.ContainsKey("FilterId") Then
                FilterId = Convert.ToInt32(Params("FilterId"))
            End If
            If FilterId = -1 Then
                Exit Sub
            End If
            Dim fc As New FilterController
            fc.Filter_Delete(PortalId, ModuleId, FilterId)

        End Sub
        Private Function GetRank() As String
            Dim RankId As Integer = -1
            If Params.ContainsKey("RankId") Then
                RankId = Convert.ToInt32(Params("RankId"))
            End If
            Dim rc As New RewardController
            Dim rank As RewardInfo = rc.Reward_Get(PortalId, ModuleId, RankId)
            Dim sOut As String = "{"
            sOut &= Utilities.JSON.Pair("RankId", rank.RankId.ToString())
            sOut &= ","
            sOut &= Utilities.JSON.Pair("RankName", rank.RankName)
            sOut &= ","
            sOut &= Utilities.JSON.Pair("MinPosts", rank.MinPosts.ToString())
            sOut &= ","
            sOut &= Utilities.JSON.Pair("MaxPosts", rank.MaxPosts.ToString())
            sOut &= ","
            sOut &= Utilities.JSON.Pair("Display", rank.Display.ToLowerInvariant().Replace("activeforums/ranks", "activeforums/images/ranks"))
            sOut &= "}"
            Return sOut
        End Function
        Private Sub RankSave()
            Dim rank As New RewardInfo()
            rank.RankId = -1
            rank.ModuleId = ModuleId
            rank.PortalId = PortalId
            If Params.ContainsKey("RankId") Then
                rank.RankId = Convert.ToInt32(Params("RankId"))
            End If
            If Params.ContainsKey("RankName") Then
                rank.RankName = Params("RankName").ToString()
            End If
            If Params.ContainsKey("MinPosts") Then
                rank.MinPosts = Convert.ToInt32(Params("MinPosts"))
            End If
            If Params.ContainsKey("MaxPosts") Then
                rank.MaxPosts = Convert.ToInt32(Params("MaxPosts"))
            End If
            If Params.ContainsKey("Display") Then
                rank.Display = Params("Display").ToString()
            End If
            Dim rc As New RewardController
            rank = rc.Reward_Save(rank)
        End Sub
        Private Sub RankDelete()
            Dim RankId As Integer = -1
            If Params.ContainsKey("RankId") Then
                RankId = Convert.ToInt32(Params("RankId"))
            End If
            If RankId = -1 Then
                Exit Sub
            End If
            Dim rc As New RewardController
            rc.Reward_Delete(PortalId, ModuleId, RankId)

        End Sub
        Private Sub PropertySave()

            Dim pc As New PropertiesController
            Dim pi As New PropertiesInfo
            pi.PropertyId = -1
            pi.PortalId = PortalId
            pi = CType(Utilities.ConvertFromHashTableToObject(Params, pi), PropertiesInfo)
            pi.Name = Utilities.CleanName(pi.Name)
            If Not String.IsNullOrEmpty(pi.ValidationExpression) Then
                pi.ValidationExpression = HttpUtility.UrlDecode(HttpUtility.HtmlDecode(pi.ValidationExpression))
            End If
            If pi.PropertyId = -1 Then
                Dim lbl As String = Params("Label").ToString
                Dim lcUtils As New LocalizationUtils
                lcUtils.SaveResource("[RESX:" & pi.Name & "].Text", lbl, PortalId)
            Else
                If Utilities.GetSharedResource("[RESX:" & pi.Name & "]").ToLowerInvariant.Trim <> Params("Label").ToString.ToLowerInvariant.Trim Then
                    Dim lcUtils As New LocalizationUtils
                    lcUtils.SaveResource("[RESX:" & pi.Name & "].Text", Params("Label").ToString, PortalId)
                End If

            End If
            pc.SaveProperty(pi)
            Dim fc As New ForumController()
            Dim fi As Forum = fc.GetForum(PortalId, ModuleId, pi.ObjectOwnerId, True)
            fi.HasProperties = True
            fc.Forums_Save(PortalId, fi, False, False)
            
        End Sub
        Private Function PropertyList() As String

            Dim sb As New StringBuilder
            Dim pc As New PropertiesController
            If Not String.IsNullOrEmpty(Params("ObjectOwnerId").ToString) Then
                Return pc.ListPropertiesJSON(PortalId, CInt(Params("ObjectType")), CInt(Params("ObjectOwnerId")))
            Else
                Return String.Empty
            End If


        End Function
        Private Function UpdateSort() As Integer

            Dim propertyId As Integer = -1
            Dim sortOrder As Integer = -1
            Dim pc As New PropertiesController
            Dim props As String = Params("props").ToString
            props = props.Remove(props.LastIndexOf("^"))
            For Each s As String In props.Split(CChar("^"))
                If Not String.IsNullOrEmpty(props) Then
                    propertyId = CInt(s.Split(CChar("|"))(0))
                    sortOrder = CInt(s.Split(CChar("|"))(1))
                    Dim pi As PropertiesInfo = pc.GetProperty(propertyId, PortalId)
                    If Not pi Is Nothing Then
                        pi.SortOrder = sortOrder
                        pc.SaveProperty(pi)
                    End If
                End If
            Next

            
        End Function
        Friend Sub PropertyDelete()

            Dim pc As New PropertiesController
            Dim prop As PropertiesInfo = pc.GetProperty(CInt(Params("propertyid")), PortalId)
            If Not prop Is Nothing Then
                pc.DeleteProperty(PortalId, CInt(Params("propertyid")))
                If Not pc.ListProperties(PortalId, prop.ObjectType, prop.ObjectOwnerId).Count > 0 Then
                    Dim fc As New ForumController()
                    Dim fi As Forum = fc.GetForum(PortalId, ModuleId, prop.ObjectOwnerId, True)
                    fi.HasProperties = False
                    fc.Forums_Save(PortalId, fi, False, False)
                End If
            End If


        End Sub
        Private Function GetLists() As String
            Dim sb As New StringBuilder
            Dim lists As New DotNetNuke.Common.Lists.ListController
            'Dim list As DotNetNuke
            Dim lc As DotNetNuke.Common.Lists.ListInfoCollection = lists.GetListInfoCollection(String.Empty, String.Empty, PortalId)
            For Each l As DotNetNuke.Common.Lists.ListInfo In lc
                If l.PortalID = PortalId Then
                    sb.Append("{")
                    sb.Append(Utilities.JSON.Pair("listname", l.Name))
                    sb.Append(",")
                    sb.Append(Utilities.JSON.Pair("listid", l.Key))
                    sb.Append("},")
                End If
            Next
            Dim sOut As String = sb.ToString
            If sOut.EndsWith(",") Then
                sOut = sOut.Substring(0, sOut.Length - 1)
                sOut = "[" & sOut & "]"
            End If
            Return sOut
        End Function
        Private Function LoadView() As String
            Dim sb As New StringBuilder
            Dim view As String = "home"
            If Not Params("view") Is Nothing Then
                view = Params("view").ToString.ToLowerInvariant
            End If
            Dim sPath As String = HttpContext.Current.Server.MapPath("~/desktopmodules/activeforums/")
            Dim sFile As String = String.Empty
            Select Case view
                Case "forumeditor"
                    sFile = Utilities.GetFile(sPath & "\admin\forumeditor.ascx")
            End Select
            Dim cpControls As New Controls.ControlPanel(PortalId, ModuleId)
            sFile = sFile.Replace("[AF:CONTROLS:SELECTTOPICSTEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.TopicsView))
            sFile = sFile.Replace("[AF:CONTROLS:SELECTTOPICTEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.TopicView))
            sFile = sFile.Replace("[AF:CONTROLS:SELECTTOPICFORMTEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.TopicForm))
            sFile = sFile.Replace("[AF:CONTROLS:SELECTREPLYFORMTEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.ReplyForm))
            sFile = sFile.Replace("[AF:CONTROLS:SELECTPROFILETEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.Profile))
            sFile = sFile.Replace("[AF:CONTROLS:SELECTEMAILTEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.Email))
            sFile = sFile.Replace("[AF:CONTROLS:SELECTMODEMAILTEMPLATES]", cpControls.TemplatesOptions(Templates.TemplateTypes.ModEmail))
            sFile = sFile.Replace("[AF:CONTROLS:GROUPFORUMS]", cpControls.ForumGroupOptions)
            sFile = sFile.Replace("[AF:CONTROLS:SECGRID:ROLES]", cpControls.BindRolesForSecurityGrid(HttpContext.Current.Server.MapPath("~/")))

            sFile = Utilities.LocalizeControl(sFile, True)
            Return sFile
        End Function




    End Class
End Namespace
